package Thread;

import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import utils.JX_Utils;
import utils.ResolveDataUtil;

/**
 * 蓝牙通讯线程
 */
public class BluetoothCommunicateThread extends Thread {
    private static final int MAX_RECEIVE_DATA = 1024;
    private static final long TIME_OUT = 2000;
    private Handler handler; // 与Service通信的Handler
    private BluetoothSocket socket;
    private InputStream inStream; // 对象输入流
    private OutputStream outStream; // 对象输出流
    StringBuffer buffer = new StringBuffer();
    StringBuffer buffer2;
    Boolean isshangban = true;
    String mingling;
    /**
     * false:停止运行
     */
    public static boolean isRun = false; // 运行标志位
    int nRet = 0;
    private byte[] recvBuffer = null;
    private byte[] sendBuffer = null;
    byte[] pBytesSend = null;
    int nLenTmp;
    private ResolveDataUtil resolveData = new ResolveDataUtil();

    String f6miyao;
    String init;
    int n = 2;
    int y = 0;

    Context context;


    // public static boolean isrun = false;

    public BluetoothCommunicateThread(Handler handler,
                                      BluetoothSocket bluetoothSocket, Context context) {
        // Log.e("88",
        // "88bluetooth socket=" + socket + ",isConnected="
        // + socket.isConnected());
        this.handler = handler;
        this.socket = bluetoothSocket;
        this.context = context;
        try {
            this.outStream = socket.getOutputStream();
            this.inStream = socket.getInputStream();

        } catch (Exception e) {
            try {
                socket.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            // 发送连接失败消息
            // SendLoop.getExceptionMessage("Error连接失败,请重连");
            Message msg = new Message();
            msg.what = 2;
            handler.sendMessage(msg);

        }

    }

    @Override
    public void run() {
        super.run();
//        recvBuffer = new byte[MAX_RECEIVE_DATA];
        while (true) {

            try {

                byte[] bytTemp = new byte[1024];
                int nRetCount = 0;
                if(inStream.available()>0 == false){
                    continue;
                }else{
                    Thread.sleep(500);
                }

                nRetCount = inStream.read(bytTemp);
                String s1 = new String(bytTemp, 0, nRetCount, "utf-8");
                Log.e("7711",s1);

                                 Message message = new Message();
                        message.what = 3;
                        message.obj = s1;
                        handler.sendMessage(message);

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }


    public void sendMessage(byte[] b) {
        if (socket != null) {
            try {
                if (b.length > 0) {
                    outStream.write(b);
                }
                outStream.flush();
                Log.e("777", "7777");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void sendMessage(String msg) {
        if (socket != null) {
            try {
                int datalen = msg.getBytes().length;
                int bytelen = 0;
                if ((datalen % 2) == 0)
                    bytelen = (int) (datalen / 2);
                else
                    bytelen = (int) (datalen / 2) + 1;

                sendBuffer = new byte[bytelen];
                int i = 0, j = 0;
                while (i < datalen) {
                    while (i >= 0 && (!CharInRange(msg.charAt(i))))
                        i++;

                    if (((i + 1) >= datalen)
                            || (!CharInRange(msg.charAt(i + 1)))) {
                        sendBuffer[j] = StrToByte(String.valueOf(msg.charAt(i)));
                        j++;
                    } else {
                        sendBuffer[j] = StrToByte(msg.substring(i, i + 2));
                        j++;
                    }

                    i += 2;
                }
                for (int m = 0; i < sendBuffer.length; m++) {
                    System.out.print(sendBuffer[m]);
                }
                outStream = new DataOutputStream(socket.getOutputStream());
                if (sendBuffer.length > 0) {
                    outStream.write(sendBuffer);
                }
                outStream.flush();
            } catch (Exception e) {
                Log.d("test", "--not connected 4--");
            }
        } else {
            Log.d("test", "--not connected 5--");
        }
    }


    // Function to send Bluetooth message
    public void SendStr(String str) {
        byte[] bf = new byte[33];
        bf = str.getBytes();
        if((!str.equals("")) && (socket!=null)) {
            try {
                outStream = socket.getOutputStream();
                outStream.write(bf);

            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (outStream != null) {
                    outStream.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private boolean CharInRange(char c) {
        boolean result = false;
        if (c >= '0' && c <= '9')
            result = true;
        if (c >= 'a' && c <= 'f')
            result = true;
        if (c >= 'A' && c <= 'F')
            result = true;
        return result;
    }

    private byte StrToByte(String s) {
        return Integer.valueOf(String.valueOf(Integer.parseInt(s, 16)))
                .byteValue();
    }


    public static int getzhi(String shi) {
        String substring = shi.substring(6, 10);
        int hexStringToInt = JX_Utils.hexStringToInt(substring);
        String substring2 = shi.substring(12, 12 + hexStringToInt * 2);
        int zong = JX_Utils.hexStringToInt(substring2);
        return zong;

    }


}
